<template>
    <button style="margin: 5px 10px 10px;" @click="setLineStyle">给连接加上样式</button>
    <div id="diagramContainer">
        <div id="item_left" class="item a">A</div>
        <div id="item_right" class="item b">B</div>
    </div>
</template>
<script lang="js" setup>
import { ref, reactive,onMounted, computed } from 'vue';
import { jsPlumb } from 'jsplumb';

const $jsPlumb = jsPlumb
const common = reactive({
    connector: ['Bezier'], // 连接线类型：贝塞尔曲线
    endpoint: ['Dot', { radius: 5, cssClass: 'circle', hoverClass: 'circle1' }], // 端点类型：圆点
    anchor: ['Left', 'Right', 'Bottom', 'Top'], // 锚点类型
})
const isSetLineSytle = ref(false)

// 初始化jsplumb
const initJsplumb = () => {
    $jsPlumb.ready(function(){
        $jsPlumb.connect({
            source: 'item_left', // 源节点
            target: 'item_right', // 目标节点
            // location 0.5 箭头在中间，location 1箭头在目标源，一条线可以有多个箭头
            overlays: [['Arrow', { width: 12, length: 12, location: 1 }]]
        }, common)
        // 配置可拖拽节点
        $jsPlumb.draggable('item_left', {
            containment: 'diagramContainer'
        })
        $jsPlumb.draggable('item_right', {
            containment: 'diagramContainer'
        })
    })
    // 给指定id元素添加锚点
    $jsPlumb.addEndpoint('item_left', { anchor: ['Left']})
}

// 配置线条样式
const setLineStyle = () => {
    isSetLineSytle.value = !isSetLineSytle.value
    const lineStyle = {
        paintStyle: isSetLineSytle.value && { stroke: 'lightgray', strokeWidth: 3 },
        endpointStyle: isSetLineSytle.value && { fill: 'lightgray', outlineStroke: 'darkgray', outlineWidth: 2 }
    }
    $jsPlumb.connect({
        source: 'item_left', // 源节点
        target: 'item_right', // 目标节点
        ...lineStyle
    }, common)
}
onMounted(() => {
    initJsplumb()
})
  
</script>

<style scoped lang="scss">
#diagramContainer {
    padding: 20px;
    height: 500px;
    border: 1px solid gray;
    display: flex;
    justify-content: space-around;
    position: relative;
}
.circle:hover {
    circle {
        fill: tomato;
    }
}
.item {
    height: 80px;
    width: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px solid #10AC84;
    font-size: 20px;
    font-weight: 600;
    cursor: move;
    &.a {
        position: absolute;
        left: 50px;
    }
    &.b {
        position: absolute;
        right: 60px;
    }
}
</style>
